import { Component, OnInit } from '@angular/core';
import {News} from '../../model/News';
import {NewsService} from '../../services/news.service';
import {Router} from '@angular/router';
import {NewsCate} from '../../model/NewsCate';
import {ConfigService} from '../../services/config.service';

@Component({
  selector: 'app-newslist',
  templateUrl: './newslist.component.html',
  styleUrls: ['./newslist.component.css']
})
export class NewslistComponent implements OnInit {
  nl:Array<News>;
  page:number;
  pagesize:number;
  total:number;
  cl:Array<NewsCate>;
  currentcate:string;


  constructor(private newsservice:NewsService
  ,private router:Router
  ,public config:ConfigService
  ) {
    this.nl=new Array();
    //this.loadNews();
    this.cl=this.newsservice.getNewsCategory();

    this.page=0;
    this.pagesize=20;
    this.total=0;




  }
//在组件初始化时执行，并且只执行一次
  ngOnInit(): void {
    this.currentcate=this.cl[0].newscateid;
    this.getNewsByPage(this.page=0);
  }
  loadNews(){
    this.newsservice.getNewsList()
      .then((data:any)=>{
        this.nl=new Array();
        this.nl=data.list;
      })
  }
  goToNewsDetail(id:string) {
    this.router.navigate(['/newsdetail', {"newsid": id}])
  }

  getNewsByPage(page:number){
    // this.newsservice.getNewsListByPage(page,this.pagesize)
    //   .then((data:any)=>{
    //   if(data.msg='ok'){
    //     this.nl=new Array();
    //     this.nl=data.obj.content;
    //     this.page=data.obj.pageable.pageNumber+1;
    //     this.total=data.obj.totalElements;
    //   }
    //   })
    this.newsservice.getNewsListByCate(this.currentcate,page,this.pagesize)
      .then((data:any)=>{
        if(data.msg='ok') {
          this.nl = new Array();
          this.nl = data.obj.content;
          this.page = data.obj.pageable.pageNumber + 1;
          this.total = data.obj.totalElements;
        }


      })

  }

  onPageChange(e){
    console.dir(e);
    let p:number=e-1;
    this.getNewsByPage(p);
  }

  onNavChange(id:string){
    console.log(id);
    this.currentcate=id;
    //this.getNewsByPage(this.page);
    this.getNewsByPage(this.page);
  }



}
